import {
  Card,
  Form,
  Input,
  Button,
  DatePicker,
  Select,
  Table,
  Tag,
  Space,
  Modal,
  message,
} from "antd"
import { useState, useEffect } from "react"
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons"
import PageHeaderWrapper from "@/components/pageHeaderWrapper"
import "./index.less"

const { TextArea } = Input
const { Option } = Select

function DailyReport() {
  const [form] = Form.useForm()
  const [reports, setReports] = useState([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingReport, setEditingReport] = useState(null)

  // 获取日报列表
  const fetchReports = async () => {
    setLoading(true)
    try {
      // 替换为实际API调用
      const response = await fetch("/api/daily-reports")
      const data = await response.json()
      setReports(data)
    } catch (error) {
      message.error("获取日报列表失败")
    } finally {
      setLoading(false)
    }
  }

  // 表格列定义
  const columns = [
    {
      title: "日期",
      dataIndex: "date",
      key: "date",
      render: (date) => new Date(date).toLocaleDateString(),
    },
    {
      title: "工作内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
    },
    {
      title: "完成情况",
      dataIndex: "status",
      key: "status",
      render: (status) => (
        <Tag color={status === "completed" ? "green" : "orange"}>
          {status === "completed" ? "已完成" : "进行中"}
        </Tag>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      const url = editingReport
        ? `/api/daily-reports/${editingReport.id}`
        : "/api/daily-reports"
      const method = editingReport ? "PUT" : "POST"

      await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      })

      message.success(editingReport ? "更新成功" : "创建成功")
      setModalVisible(false)
      form.resetFields()
      fetchReports()
    } catch (error) {
      message.error(editingReport ? "更新失败" : "创建失败")
    }
  }

  // 处理编辑
  const handleEdit = (report) => {
    setEditingReport(report)
    form.setFieldsValue({
      ...report,
      date: moment(report.date),
    })
    setModalVisible(true)
  }

  // 处理删除
  const handleDelete = (report) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这条日报吗？",
      onOk: async () => {
        try {
          await fetch(`/api/daily-reports/${report.id}`, {
            method: "DELETE",
          })
          message.success("删除成功")
          fetchReports()
        } catch (error) {
          message.error("删除失败")
        }
      },
    })
  }

  // 处理新增
  const handleAdd = () => {
    setEditingReport(null)
    form.resetFields()
    setModalVisible(true)
  }

  useEffect(() => {
    fetchReports()
  }, [])

  return (
    <>
      <PageHeaderWrapper title="日报管理" subtitle="记录每日工作内容" />
      <section className="G-main">
        <Card
          title="日报列表"
          extra={
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新建日报
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={reports}
            loading={loading}
            rowKey="id"
            pagination={{
              defaultPageSize: 10,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
          />
        </Card>

        <Modal
          title={editingReport ? "编辑日报" : "新建日报"}
          open={modalVisible}
          onOk={() => form.submit()}
          onCancel={() => {
            setModalVisible(false)
            form.resetFields()
          }}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              name="date"
              label="日期"
              rules={[{ required: true, message: "请选择日期" }]}
            >
              <DatePicker style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              name="content"
              label="工作内容"
              rules={[{ required: true, message: "请输入工作内容" }]}
            >
              <TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="status"
              label="完成情况"
              rules={[{ required: true, message: "请选择完成情况" }]}
            >
              <Select>
                <Option value="completed">已完成</Option>
                <Option value="inProgress">进行中</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </section>
    </>
  )
}

export default DailyReport
